/*
 * @Author: zhi1hw hanwei@zhi1tech.com
 * @Date: 2024-06-16 12:11:03
 * @LastEditors: zhi1hw hanwei@zhi1tech.com
 * @LastEditTime: 2024-07-14 16:17:19
 * @FilePath: \code\src\plugins\request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
interface IRequestConfig extends AxiosRequestConfig {
  apiLoading?: string
}
// create an axios instance
const server = axios.create({
  baseURL: '/api',  // 使用代理前缀
  timeout: 300000,
  headers: {
    // "Authorization":'Bearer '+ localStorage.getItem('token')
        'Authorization': 'Bearer pat_GOWmZqRKSnRuHlcl01UDHK56nmCPTKMKVJgWljdgxysH3RDU28ujSrPslWFZnyg3',
  }
})
const CancelToken = axios.CancelToken;
/**
 * 请求拦截器
 */
server.interceptors.request.use((config: AxiosRequestConfig | any) => {
  if(localStorage.getItem('token') ) {
    // config.headers["Authorization"] ='Bearer '+( config.headers? config.headers.Authorization: localStorage.getItem('token'))
    config.headers["Authorization"] = 'Bearer pat_GOWmZqRKSnRuHlcl01UDHK56nmCPTKMKVJgWljdgxysH3RDU28ujSrPslWFZnyg3'
  
    
  }
  return config
}, err => {
  if (axios.isCancel(err)) {
    console.log('取消本次请求', err.message); // err.message 是调用 source.cancel('取消成功'); 传入的参数
    return Promise.reject(err);
  } else {
    return Promise.reject(err);
  }
})

axios.interceptors.response.use(res => {
  console.log(res)
  // 对结果数据进行操作
  return res
}, err => {
  //接口处理错误
  return Promise.reject(err)
})
export interface IApi {
  request(config: IRequestConfig): Promise<any>
  get(url: string, data?: any, config?: any): Promise<unknown>
  post(url: string, data?: any, config?: any): Promise<unknown>
}
const isMobile = function () {
  const userAgent = navigator.userAgent.toLowerCase();
  return /iphone|ipod|android|windows phone|blackberry|bb10|mobi|xoom|tablet|mobile/i.test(
    userAgent
  );
};
const api: IApi = {
  request(config: IRequestConfig) {
    return new Promise((resolve: (value: unknown) => void, reject: (value: unknown) => void) => {
      server.request(config).then(res => {
        /**
         * @param{status -> code}
         * 200: 请求成功
         */
        if (res.status === 200) {
          if (res.data.code === 401) {
            if (isMobile()) {
              if (process.env.NODE_ENV === 'development') {
                // location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorize`;
              } else if (process.env.NODE_ENV === 'test') {
                location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
              } else {
                location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
              }
            } else {
              if (process.env.NODE_ENV === 'development') {
                // location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorizeAAD`;
              } else if (process.env.NODE_ENV === 'test') {
                location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
              } else {
                location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
              }
            }
            console.log('token过期')
            return
          } else {
            resolve(res.data)
          }

        } else {
          reject(res)
        }
      }).catch(e => {
        reject(e)
      })
    })
  },
  get(url: string, data?: any, config?: IRequestConfig) {
    let requestConfig: IRequestConfig = {
      method: "GET",
      url: url,
      params: data,
      ...config,
    }
    return new Promise((resolve: (value: unknown) => void, reject: (value: unknown) => void) => {
      this.request(requestConfig).then(res => {
        resolve(res.data)
      }).catch(e => {
        reject(e)
      })
    })
  },
  post(url: string, data?: any, config?: IRequestConfig) {
    let requestConfig = {
      method: "POST",
      url: url,
      data: data,
      ...config,
    }

    return new Promise((resolve: (value: unknown) => void, reject: (value: unknown) => void) => {
      this.request(requestConfig).then(res => {
        resolve(res.data)
      }).catch(e => {
        reject(e)
      })
    })
  }
}
export default api